package com.xinqi.modules.chat.third.utils;

import cn.hutool.core.lang.UUID;
import cn.jiguang.common.utils.StringUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.xinqi.modules.chat.favorite.controller.web.utils.DateUtils;
import com.xinqi.modules.chat.third.domain.FileInsertBean;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class OssUtils {
    private static String endpoint = "oss-cn-hangzhou.aliyuncs.com";

    private static String accessKeyId = "LTAI5tPkfy1BZy6hD94Meo9u";

    private static String accessKeySecret = "JRytVZhuB89f3ETeH1udYXznfMQK7R";

    private static String bucketName = "xinqiclass";

    private static String urlStart = "http://xinqiclass.oss-cn-hangzhou.aliyuncs.com/";

    private static String urlStarts = "https://xinqiclass.oss-cn-hangzhou.aliyuncs.com";

    private static String COURSE = "course";

    private static final String TEMPORARY_PATH = "temp";

    /**
     * 上传流文件
     */
    public static FileInsertBean uploadFileInsertBean(String filename, Integer type, InputStream inputStream) throws URISyntaxException {
        FileInsertBean insert = new FileInsertBean();
        BufferedImage bufferedImage = null;
        String path = Paths.get(Objects.requireNonNull(OssUtils.class.getClassLoader().getResource("")).toURI()).toString();

        if (filename == null || StringUtils.isEmpty(filename)) {
            filename = COURSE + "/" + UUID.randomUUID() + "-" + DateUtils.dateTimeNow() + ".png";
        }
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            insert.setSize(Long.valueOf(inputStream.available()));
            bufferedImage = ImageIO.read(inputStream);

            saveTemplate(bufferedImage, path, filename);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        InputStream ins = null;
        try {
            ins = Files.newInputStream(Paths.get(path + TEMPORARY_PATH + "/" + filename));
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filename, ins);
            // 设置该属性可以返回response。如果不设置，则返回的response为空。
            putObjectRequest.setProcess("true");
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 宽度
            insert.setWidth(Long.valueOf(bufferedImage.getWidth()));
            // 高度
            insert.setHeight(Long.valueOf(bufferedImage.getHeight()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            ossClient.shutdown();
            //删除临时文件
            deleteTemporaryFile(path + TEMPORARY_PATH + "/" + filename);
        }

        insert.setFilename(filename);
        insert.setFileurl(urlStarts + "/" + filename);
        insert.setType(type);
        insert.setOss_fileName(filename);
        insert.setUrl(urlStarts + "/" + filename);
        insert.setDuration(0L);
        return insert;
    }

    public static String ossUploadLocal(String local) {
        String targetPath = "";
        try {
            File file = new File(local);
            long size = file.length();
            //创建OSSClient实例
            //获取上传文件输入流
            InputStream inputStream = new FileInputStream(local);
            //获取文件名称
            String fileName = file.getName();

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM-dd");
            String datePath = simpleDateFormat.format(new Date()).toString();
            //拼接
            String targetfileName = datePath + "/" + fileName;
            OSS ossUpladClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossUpladClient.putObject(bucketName, targetfileName, inputStream);

            targetPath = "https://" + bucketName + "." + endpoint + "/" + targetfileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return targetPath;
    }

    public static String ossUploadInputStream(String fileName, InputStream inputStream) {
        String targetPath = "";
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM-dd");
            String datePath = simpleDateFormat.format(new Date()).toString();
            //拼接
            String targetfileName = datePath + "/" + fileName;
            OSS ossUpladClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossUpladClient.putObject(bucketName, targetfileName, inputStream);

            targetPath = "https://" + bucketName + "." + endpoint + "/" + targetfileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return targetPath;
    }

    /**
     * 临时文件
     *
     * @param bufferedImage
     * @param path
     * @param filename
     * @throws IOException
     */
    private static void saveTemplate(BufferedImage bufferedImage, String path, String filename) throws IOException {
        File upload = new File(path + TEMPORARY_PATH + "/", filename);
        if (!upload.exists()) {
            upload.mkdirs();
        }
        ImageIO.write(bufferedImage, "png", upload);
    }

    private static void deleteTemporaryFile(String path) {
        File fileDelete = new File(path);
        fileDelete.delete();
    }

    /**
     * 从网络Url中读取文件* @param urlStr 文件URL地址* @throws IOException
     */
    public static InputStream downLoadFromUrl(String urlStr) throws IOException {
        //把地址转换成URL对象
        URL url = new URL(urlStr);
        // 创建http链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        // 防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        // 得到输入流
        return conn.getInputStream();
    }
}
